package com.lollipop.rabbitmq.three;

import com.lollipop.rabbitmq.util.RabbitMqUtiils;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @Author: Lollipop
 * @Date: 2021-10-03 18:00
 * @Description: 测试时启动两个Worker02(IDEA多实例启动)，修改System.out.println("消费者A");表示不同的实例
 * 会发现同一个生产者生产消息，两个消费者交替消费消息，同一个消息，同时只有一个消费者消费
 */
public class Worker0201 {
    public static final String TASK_QUEUE_NAME = "ack_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 输出表示不同的实例
        System.out.println("消费者A");
        Channel channel = RabbitMqUtiils.getChannel();

        // 预取值 设置不公平分发 观察现象：处理速度快的优先处理消息
        int prefetchCount = 1;
        channel.basicQos(prefetchCount);

        // 使用手动应答
        boolean autoAck = false;

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("消费者接收到的消息：" + new String(message.getBody(),"utf-8"));
            /**
             * 消息标记tag
             * 是否批量应答false
             */
            channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
        };
        CancelCallback cancelCallback = consumerTag -> System.out.println(consumerTag+"消费者取消消费接口回调逻辑");
        channel.basicConsume(TASK_QUEUE_NAME, autoAck, deliverCallback, cancelCallback);
    }
}
